<template>
  <div class="card">
    <el-avatar :size="90" :src="require('../assets/avatar/'+userId+'.jpg')" class="pic" @click="up=true"></el-avatar>
    <el-dialog v-model="up" width="40%" center title="更换头像" :close-on-click-modal = "true">
    <div class="up-box">
      <el-upload
    class="avatar-uploader"
    :action="actionUrl"
    name="pic"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
    </div>
  </el-dialog>
    <h2 class="email">{{ userEmail }}</h2>
    <span class="detail"><span @click="toLike">点赞{{likeNum}}&nbsp;</span>|<span @click="toCollect">&nbsp;收藏{{collectNum}}&nbsp;</span>|
    <span @click="toCard">卡片{{ cardNum }}&nbsp;</span>|<span>&nbsp;感想{{blogNum}}&emsp;</span>
      <el-button @click="toEdit" type="info">编辑资料+</el-button>
      <el-button class="writeblog" @click="centerDialogVisible = true" type="primary">发表感想</el-button>
      <el-popover placement="bottom" trigger="hover" :width="160" content="将从个人卡片中抽取一组熟练度较低的卡片进行复习">
      <template #reference>
        <el-button class="review" type="success" @click="toReview">复习卡片</el-button>
      </template>
      </el-popover>
    </span>
  </div>
  <el-dialog v-model="centerDialogVisible" width="40%" center title="发表感想" :close-on-click-modal = "false">
    <el-form :model="blogForm">
      <el-form-item label="主题" prop="title">
        <el-input placeholder="主题" v-model="blogForm.blog_title"></el-input>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input type="textarea" placeholder="这一刻的想法..." autosize v-model="blogForm.blog_content"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="writeBlog">发表</el-button>
      </span>
    </template>
  </el-dialog>
  <div class="blog">
    <div v-for="blog of blogList" :key="blog">
      <h3 class="title">#&nbsp;{{ blog.blog_title }}</h3>
      <div class="content">{{ blog.blog_content }}</div>
      <div class="date">{{ blog.blog_date }}</div>
      <el-popconfirm width="220"
    confirm-button-text="确认"
    cancel-button-text="取消"
    title="您确认要删除此感想吗？"
    @confirm="deleteBlog(blog.blog_id)"
    >
    <template #reference>
      <el-button class="button" text>删除</el-button>
    </template>
  </el-popconfirm>
      <el-divider></el-divider>
    </div>
    <el-divider v-show="nothing">有什么感想，写下来吧</el-divider>
  </div>
</template>

<script lang="ts">
import { ElMessage } from 'element-plus'
import { defineComponent, ref, reactive } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { Plus } from '@element-plus/icons'
import type { UploadProps } from 'element-plus'
export default defineComponent({
  name: 'IndividualView',
  setup () {
    const centerDialogVisible = ref(false)
    const up = ref(false)
    const userEmail = sessionStorage.getItem('userE')
    const userId = sessionStorage.getItem('userId')
    const likeNum = ref(0)
    const collectNum = ref(0)
    const cardNum = ref(0)
    const blogNum = ref(0)
    const imageUrl = ref('')
    const actionUrl = ref('http://localhost:8081/upload/' + userId)
    const router = useRouter()
    const blogList: any = ref(null)
    const nothing = ref(false)
    const blogForm = reactive({
      blog_title: '',
      blog_content: '',
      user_id: userId
    })
    const toEdit = () => {
      router.push('/edit')
    }
    const getLike = () => {
      axios.post('http://localhost:8081/getLike', { user_id: userId }).then(res => {
        if (res.data !== null) {
          likeNum.value = res.data
        } else if (res.data === 'error') {
          console.log('getLikeError')
        }
      }).catch(error => {
        console.log(error)
      })
    }
    const getCollect = () => {
      axios.post('http://localhost:8081/getCollect', { user_id: userId }).then(res => {
        if (res.data !== null) {
          collectNum.value = res.data
        } else if (res.data === 'error') {
          console.log('getLikeError')
        }
      }).catch(error => {
        console.log(error)
      })
    }
    const countCard = () => {
      axios.post('http://localhost:8081/countCard', { user_id: userId }).then(res => {
        if (res.data !== null) {
          cardNum.value = res.data
        } else if (res.data === 'error') {
          console.log('getCardError')
        }
      }).catch(error => {
        console.log(error)
      })
    }
    const countBlog = () => {
      axios.post('http://localhost:8081/countBlog', { user_id: userId }).then(res => {
        if (res.data !== null) {
          blogNum.value = res.data
          if (blogNum.value === 0) {
            nothing.value = true
          }
        } else if (res.data === 'error') {
          console.log('getBlogNumError')
        }
      }).catch(error => {
        console.log(error)
      })
    }
    const writeBlog = () => {
      if (blogForm.blog_title === '' || blogForm.blog_content === '') {
        ElMessage.success('请填写完整内容')
      } else {
        axios.post('http://localhost:8081/writeBlog', blogForm).then(res => {
          if (res.data !== null) {
            centerDialogVisible.value = false
            location.reload()
            ElMessage.success('发表成功')
          } else {
            ElMessage.success('服务器繁忙')
          }
        }).catch(error => {
          console.log(error)
        })
      }
    }
    const getBlog = () => {
      axios.post('http://localhost:8081/getBlog', { user_id: userId }).then(res => {
        if (res.data !== null) {
          blogList.value = res.data
        } else {
          console.log('error')
        }
      }).catch(error => {
        console.log(error)
      })
    }
    const deleteBlog = (item: any) => {
      axios.post('http://localhost:8081/deleteBlog', { blog_id: item }).then(res => {
        if (res.data === 'ok') {
          location.reload()
          ElMessage.success('删除成功')
        } else {
          console.log('error')
        }
      }).catch(error => {
        console.log(error)
      })
    }
    const toLike = () => {
      router.push({ name: 'like', query: { usId: userId } })
    }
    const toCollect = () => {
      router.push({ name: 'collect', query: { usId: userId } })
    }
    const toCard = () => {
      router.push({ name: 'card', query: { usId: userId } })
    }
    const toReview = () => {
      router.push('/review')
    }
    const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
      imageUrl.value = URL.createObjectURL(uploadFile.raw!)
      ElMessage.success('更换成功!')
      up.value = false
    }
    const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
      if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
      }
      return true
    }
    getBlog()
    getLike()
    getCollect()
    countBlog()
    countCard()
    return {
      userEmail,
      toEdit,
      likeNum,
      collectNum,
      cardNum,
      blogNum,
      writeBlog,
      centerDialogVisible,
      blogForm,
      blogList,
      toLike,
      toCollect,
      toCard,
      toReview,
      deleteBlog,
      up,
      handleAvatarSuccess,
      beforeAvatarUpload,
      imageUrl,
      actionUrl,
      userId,
      nothing
    }
  },
  components: { Plus }
})
</script>
<style scoped>
.card{
  position: relative;
  top: 80px;
  width: 700px;
  height: 130px;
  margin-top: 20px;
  margin-left: 130px;
}
.pic{
  position: absolute;
  left: 0px;
  top: 20px;
}
.email{
  position: absolute;
  left: 120px;
  top: 10px;
}
.detail{
  position: absolute;
  left: 120px;
  top: 80px;
  cursor: pointer;
}
.blog{
  position: relative;
  top: 100px;
  width: 700px;
  height: auto;
  margin-top: 20px;
  margin-left: 130px;
}
.writeblog{
  position: absolute;
  margin-left: 10px;
}
.review{
  position: absolute;
  margin-left: 107px;
}
.title{
  text-align: left;
  white-space: pre-wrap;
}
.content{
  text-align: left;
  white-space: pre-wrap;
}
.date{
  color: gray;
  font-size: small;
  text-align: left;
  margin-top: 15px;
}
.button{
  float: right;
  margin-bottom: 25px;
  height: 25px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.up-box{
  margin-left: 135px;
}
</style>
<style>
.el-textarea__inner {
    width: 421px !important;
}
</style>
